package utils

import (
	"clouds.lgb24kcs.cn/global"
	"errors"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"math/rand"
	"strconv"
	"time"
)

/**
* 使⽤AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 您的AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}
func _main(mobime string, code string) (_err error) {
	client, _err := CreateClient(tea.String("LTAI5t91y45gyMiANH3hvbS8"), tea.String("17NtaUoayHVp9MceCAd8GOFmjizAE2"))
	if _err != nil {
		return _err
	}
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(mobime),
		SignName:      tea.String("ABC商城"),
		TemplateCode:  tea.String("SMS_205621477"),
		TemplateParam: tea.String(fmt.Sprintf("{\"code\":%s}", code)),
		//TemplateParam: tea.String("{\"code\":\"1234\"}"),
	}
	// 复制代码运⾏请⾃⾏打印 API 的返回值
	res, _err := client.SendSms(sendSmsRequest)
	if _err != nil {
		global.APP.Log.Error(_err.Error())
		return _err
	} else {
		if *res.Body.Code == "OK" {
			// 将code存入redis
			_err = Set(mobime, code)
			if _err != nil {
				global.APP.Log.Error(_err.Error())
				return _err
			} else {
				return nil
			}
		} else {

			_err = errors.New(*res.Body.Message)
			global.APP.Log.Error(_err.Error())

			return _err
		}
	}
}
func SendSMCode(Mobile string) error {
	// 生成6位数的整数
	rand.Seed(time.Now().UnixNano())
	num := rand.Intn(900000) + 100000 // rand.Intn()中的位数就表示生成多少为的数字，比如这是是十万，表示生成6位数
	err := _main(Mobile, strconv.Itoa(num))
	if err != nil {
		global.APP.Log.Error(err.Error())
		return err
	}
	return nil
}
